/**
 * 用户认证相关接口
 */

import { getApiBaseUrl } from "@/utils/env";
import { getStorage } from "@/utils/storage";

const BASE_URL = getApiBaseUrl();

/**
 * 微信小程序登录
 * @param {string} code 微信登录code
 * @returns {Promise}
 */
export function loginWeixin(code) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/auth/weixin/login`,
      method: "POST",
      data: {
        code: code
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const response = res.data;
          
          // 兼容两种格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            resolve(response.data);
          } else if (response && typeof response === 'object' && response.token) {
            resolve(response);
          } else {
            reject(new Error('登录响应格式错误'));
          }
        } else {
          reject(new Error(`登录失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 游客登录（H5）
 * @param {string} visitorId 游客ID（可选）
 * @param {string} platform 平台标识
 * @returns {Promise}
 */
export function loginGuest(visitorId, platform = 'h5') {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/api/auth/guest/login`,
      method: "POST",
      data: {
        visitorId: visitorId,
        platform: platform
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const response = res.data;
          
          // 兼容两种格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            resolve(response.data);
          } else if (response && typeof response === 'object' && response.token) {
            resolve(response);
          } else {
            reject(new Error('登录响应格式错误'));
          }
        } else {
          reject(new Error(`登录失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

/**
 * 验证 token
 * @returns {Promise}
 */
export function verifyToken() {
  return new Promise((resolve, reject) => {
    // 使用 getStorage 工具函数，它会自动处理 JSON 解析
    const token = getStorage('user_token');
    
    if (!token) {
      reject(new Error('未登录'));
      return;
    }
    
    uni.request({
      url: `${BASE_URL}/api/auth/verify`,
      method: "GET",
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const response = res.data;
          
          // 兼容两种格式
          if (response && typeof response === 'object' && response.code === 200 && response.data) {
            resolve(response.data);
          } else if (response && typeof response === 'object' && response.valid) {
            resolve(response);
          } else {
            reject(new Error('验证响应格式错误'));
          }
        } else if (res.statusCode === 401) {
          reject(new Error('token无效'));
        } else {
          reject(new Error(`验证失败: ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}

